/**
 * 
 */
package com.scpii.universal.struts.manage;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.scpii.universal.action.BaseAction;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.hibernate.entity.AppTab;
import com.scpii.universal.hibernate.entity.AppUpdateTab;
import com.scpii.universal.hibernate.entity.EnterpriseTab;
import com.scpii.universal.hibernate.entity.ManageUserTab;
import com.scpii.universal.hibernate.entity.TypeTab;
import com.scpii.universal.service.AppService;
import com.scpii.universal.service.AppUpdateService;
import com.scpii.universal.service.EnterpriseService;
import com.scpii.universal.service.ManageUserService;
import com.scpii.universal.util.CacheUtil;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.UtilTool;

/**
 * universalWeb
 * 
 * @author weny 2012-7-9下午05:20:49
 */
@Controller
@Scope("prototype")
public class LoginAction extends BaseAction {
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 4629317011625914415L;
	@Resource
	private ManageUserService manageUserService;
	@Resource
	private AppService appService;
	@Resource
	private EnterpriseService enterpriseService;
	@Resource
	private AppUpdateService appUpdateService;
	private JSONObject jsonObject = new JSONObject();
	private ManageUserTab manageUserInfo;
	private ManageUserTab produceUserInfo = new ManageUserTab();
	private UserInfoDto userInfoDto = new UserInfoDto();
	private EnterpriseTab enterpriseInfo = new EnterpriseTab();

	private File enterpImgUrl;
	// 企业行业列表
	private List<TypeTab> typeEnterList;

	// 用户选择的企业类型
	private Integer intTypeId;

	private List<EnterpriseTab> enterList;

	//
	/**
	 * 企业用户登录验证
	 * 
	 * @return
	 */
	public String loginUser() {
		UserInfoDto loginedUserInfoDto = (UserInfoDto) session.getAttribute(GenericConstants.USER_INFO);
		if (manageUserInfo != null) {
			if (loginedUserInfoDto!=null && !loginedUserInfoDto.getVarLoginName().equals(manageUserInfo.getVarLoginName())){
				this.addActionError("该浏览器已登录了一个帐号，建议注销后再登录");
				return INPUT;
			}
			//admin页面登录
			if("supermanager".equals(manageUserInfo.getVarLoginName()) && "guatianlixia".equals(manageUserInfo
					.getVarPassword())){
				session.setAttribute(GenericConstants.USER_INFO,
						userInfoDto);
				return "admin";
			}
			
			String userName = manageUserInfo.getVarLoginName();
			if(StringUtils.isBlank(userName) || StringUtils.isBlank(manageUserInfo
					.getVarPassword())) {
				this.addActionError("用户名或密码错误");
				return INPUT;
			}
			
			String userPassword = CacheUtil.generatePassword(manageUserInfo
					.getVarPassword());
			if (userName.trim() != null && userPassword.trim() != null) {
				List<ManageUserTab> manageUserTabList = manageUserService
						.manageUserLogin(userName, userPassword);
				ManageUserTab userInfo = new ManageUserTab();
				if (manageUserTabList != null && manageUserTabList.size() == 1) {

					userInfo = manageUserTabList.get(0);

					// varRoleType=0：生成平台账号；varRoleType=1：后台管理平台
					if (userInfo != null && userInfo.getVarRoleType() != null
							&& userInfo.getVarRoleType() == 0) {
						/*//保存session并通过userId生成一个唯一key
						SessionUtil.saveSession(session, response, new Date(
								System.currentTimeMillis() + 20 * 60 * 1000),
								userInfo.getIntUserId().toString());
						Map<String,Object> rs= SessionUtil.getSession(request);
						//从memorycache中取得session并重新赋值
						session = (HttpSession) rs.get(SessionUtil.SESSION);
						//取得session key
						key = rs.get(SessionUtil.SESSION_KEY).toString();*/
						
						userInfoDto.setIntEnterpId(userInfo.getIntEnterpId());
						userInfoDto.setIntUserId(userInfo.getIntUserId());
						userInfoDto.setVarLoginName(userInfo.getVarLoginName());
						if (userInfo.getIntAppId() != null && userInfo.getIntAppId() != 0) {
							userInfoDto.setAppId(userInfo.getIntAppId());
							String[] properties = { "intAppUpdateId",
									"intIconId", "intAppOsType", "varAppSign",
									"dobAppVersion", "varAppDownloadUrl",
									"intLoadingIconId", "intAppBackgImgId",
									"intAppNavigateBgImgId",
									"intAppTitleBgImgId","varIosInstallUrl",
									"intAppSecondTitleImgId"};
							// Android应用最新版本的信息
							AppUpdateTab androidAppUpd = appUpdateService.getVersionUpdateInfo(userInfo.getIntAppId(), properties, GenericConstants.OPERATION_SYS_ANDROID);
							// IOS应用最新版本的信息
							AppUpdateTab iosAppUpd = appUpdateService.getVersionUpdateInfo(userInfo.getIntAppId(), properties, GenericConstants.OPERATION_SYS_IOS);
							userInfoDto.setAndroidVersionUpdate(androidAppUpd);
							userInfoDto.setIosVersionUpdate(iosAppUpd);
							userInfoDto.setAppLoadingIconId(androidAppUpd.getIntLoadingIconId());
							userInfoDto.setType(0);
						}
						// 生成临时应用icon名字
						session.setAttribute(
								GenericConstants.TEMP_APP_ICON_SESSION,
								FileUploadUtil.generateIconName() + "_"
										+ GenericConstants.APP_LOGO_SUFFIX);
						// 生成临时分类缩略图名字
						session.setAttribute(
								GenericConstants.TEMP_CATELOG_ICON_SESSION,
								FileUploadUtil.generateIconName() + "_"
										+ GenericConstants.CATELOG_ICON_SUFFIX);
						session.setAttribute(GenericConstants.USER_INFO,
								userInfoDto);
						//session内赋值后保存session进cache
//						SessionUtil.saveSession(session,key);
						return "PRODUCE_SUC";
					} else if (userInfo != null
							&& userInfo.getVarRoleType() != null
							&& userInfo.getVarRoleType() == 1) {
						//if (judgeApp(userInfo.getIntAppId())) {
						 if (userInfo.getIntAppId()!=null&&userInfo.getIntAppId()!=0) {
							/*SessionUtil.saveSession(session, response, new Date(
									System.currentTimeMillis() + 20 * 60 * 1000),
									userInfo.getIntUserId().toString());
							Map<String,Object> rs= SessionUtil.getSession(request);
							session = (HttpSession) rs.get(SessionUtil.SESSION);
							key = rs.get(SessionUtil.SESSION_KEY).toString();*/
							
							userInfoDto.setAppId(userInfo.getIntAppId());
							userInfoDto.setIntEnterpId(userInfo
									.getIntEnterpId());
							userInfoDto.setIntUserId(userInfo.getIntUserId());
							userInfoDto.setVarLoginName(userInfo
									.getVarLoginName());
							userInfoDto.setType(1);

							session.setAttribute(GenericConstants.USER_INFO,
									userInfoDto);
//							SessionUtil.saveSession(session,key);
							return "MANAGE_SUC";
						} else {
							this.addActionError("对不起，由于该账号尚未生成应用，请生成应用后再访问内容管理平台，谢谢。");
							return INPUT;
						}
					}
				} else {
					// 设置登录失败信息
					this.addActionError("用户名或密码错误");
					return INPUT;
				}
			}
		} else {
			if ( loginedUserInfoDto != null ){
				if(loginedUserInfoDto.getType() == 0)
					return "PRODUCE_SUC";
				else 
					return "MANAGE_SUC";
			}
		}
		// 设置登录失败信息
		this.addActionError("用户名或密码错误");
		return INPUT;
	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	public String quitLogin() {		
//		session.removeAttribute(GenericConstants.USER_INFO);
		session.invalidate();
		return SUCCESS;
	}

	/**
	 * 注册生成平台账号、管理平台账号
	 * 
	 * @return
	 * @author weny 2012-7-10下午04:45:31
	 */
	public String registeUser() {
		String dateString = UtilTool.dateToString(new Date());
		String paireKey = dateString.replaceAll("-", "").replaceAll(":", "")
				.replaceAll(" ", "");
		manageUserInfo.setIntEnterpId(produceUserInfo.getIntEnterpId());
		manageUserInfo.setDatUpdateDatetime(dateString);
		manageUserInfo.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		//manageUserInfo.setIntAppId(Integer.parseInt(appid));
		manageUserInfo.setVarPaireKey(paireKey);
		manageUserInfo.setVarPassword(CacheUtil.generatePassword(manageUserInfo
				.getVarPassword()));
		manageUserService.save(manageUserInfo);
		//produceUserInfo.setIntEnterpId(manageUserInfo.getIntEnterpId());
		produceUserInfo.setDatUpdateDatetime(dateString);
		produceUserInfo.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		//produceUserInfo.setIntAppId(Integer.parseInt(appid));
		produceUserInfo.setVarPaireKey(paireKey);
		produceUserInfo.setVarPassword(CacheUtil
				.generatePassword(produceUserInfo.getVarPassword()));
		manageUserService.save(produceUserInfo);
		return "SUC";
	}

	/**
	 * 判断账号下的appid是否是已经生成的应用
	 * 
	 * @param appId
	 * @return
	 * @author weny 2012-7-10下午04:46:29
	 */
	public boolean judgeApp(int appId) {
		AppTab appinfo = new AppTab();
		appinfo = appService.get(appId);
		if (appinfo != null) {
			return true;
		}
		return false;
	}

	/**
	 * 判断注册名是否存在
	 * 
	 * @return
	 * @author weny 2012-7-12上午09:47:21
	 * @throws UnsupportedEncodingException 
	 */
	public String checkLoginName() throws UnsupportedEncodingException {
		String username = request.getParameter("username");
		username = URLDecoder.decode(URLDecoder.decode(username,"UTF-8"),"UTF-8");
		Map jsonMap = new HashMap();
		if (username != null) {
			List<ManageUserTab> manageUserTabList = manageUserService
					.checkUserName(username);
			if (manageUserTabList != null && manageUserTabList.size() > 0) {
				// 账号已经存在
				jsonMap.put("state", 0);
			} else {
				// 账号不存在
				jsonMap.put("state", 1);
			}
		}
		jsonObject = JSONObject.fromObject(jsonMap);
		return "OK";
	}

	/**
	 * 跳转到登陆页面
	 * 
	 * @return
	 * @author zhangqiang 2012-7-25下午08:47:14
	 */
	public String goLogin() {
		return SUCCESS;

	}

	/**
	 * 跳转到企业注册
	 * 
	 * @return
	 * @author zhangqiang 2012-8-2下午02:19:42
	 */
	public String goEnterReg() {

		// 取得企业行业列表typeEnterList
		typeEnterList = enterpriseService.getEnterType();

		return SUCCESS;
	}

	/**
	 * 企业注册
	 * 
	 * @return
	 * @author weny 2012-7-12上午09:49:40
	 */
	public String registeEnterprise() {
		// Integer enterpId = enterpriseService.getNextEnterpId();

		// qiye zhuce
		enterpriseService.updateEnter(enterpriseInfo, enterpImgUrl, getWebAppsRealPath());

		return "SUC";
	}

	/**
	 * 跳转到个人注册
	 * 
	 * @return
	 * @author zhangqiang 2012-8-2上午10:18:30
	 */
	public String goPersonLogin() {

		// 取得企业行业列表typeEnterList
		typeEnterList = enterpriseService.getEnterType();
		return SUCCESS;
	}

	/**
	 * 获取企业类表
	 * 
	 * @return
	 * @author zhangqiang 2012-8-2上午10:41:26
	 */
	public String getEnterInfoList() {
		// 企业信息列表
		enterList = enterpriseService.getEnterListByTypeId(intTypeId);

		return SUCCESS;
	}

	// ====get()set()方法集==============
	public ManageUserTab getManageUserInfo() {
		return manageUserInfo;
	}

	public void setManageUserInfo(ManageUserTab manageUserInfo) {
		this.manageUserInfo = manageUserInfo;
	}

	public ManageUserTab getProduceUserInfo() {
		return produceUserInfo;
	}

	public void setProduceUserInfo(ManageUserTab produceUserInfo) {
		this.produceUserInfo = produceUserInfo;
	}

	public EnterpriseTab getEnterpriseInfo() {
		return enterpriseInfo;
	}

	public void setEnterpriseInfo(EnterpriseTab enterpriseInfo) {
		this.enterpriseInfo = enterpriseInfo;
	}

	public File getEnterpImgUrl() {
		return enterpImgUrl;
	}

	public void setEnterpImgUrl(File enterpImgUrl) {
		this.enterpImgUrl = enterpImgUrl;
	}

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public List<TypeTab> getTypeEnterList() {
		return typeEnterList;
	}

	public void setTypeEnterList(List<TypeTab> typeEnterList) {
		this.typeEnterList = typeEnterList;
	}

	public Integer getIntTypeId() {
		return intTypeId;
	}

	public void setIntTypeId(Integer intTypeId) {
		this.intTypeId = intTypeId;
	}

	public List<EnterpriseTab> getEnterList() {
		return enterList;
	}

	public void setEnterList(List<EnterpriseTab> enterList) {
		this.enterList = enterList;
	}

}
